import Moment from "moment";
import api from "@/server/userConfig";
/**
 * getXAxis（）方法作用：获取开始日期和结束日期之间（包含开始日期和结束日期）的日期数组，可作为时间轴坐标等
 * @param  filters: {tab:0/1/2, startTime:开始日期, endTime:结束日期}
 * 说明： tab：取值0或1或2，分别表示日、月、年，对应的startTime和endTime的格式分别为'YYYY-MM-DD'、'YYYY-MM'、'YYYY'
 */

function buildDateAxis(parames) {
  let { timeFormat, startTime, endTime } = parames;
  // 计算两个日期之间间隔的天数,月数,年数
  let length = 0; //日期跨度变量

  if (timeFormat == "days") {
    length = Moment(endTime).diff(Moment(startTime), "days");
  } else if (timeFormat == "months") {
    length = Moment(endTime).diff(Moment(startTime), "months");
  } else if (timeFormat == "years") {
    length = Moment(endTime).diff(Moment(startTime), "years");
  }

  let xAxis = new Array(length + 1);

  for (let index = 0; index < xAxis.length; index++) {
    if (timeFormat == "days") {
      xAxis[index] = Moment(startTime)
        .add(index, "days")
        .format("YYYY-MM-DD");
    } else if (timeFormat == "months") {
      xAxis[index] = Moment(startTime)
        .add(index, "months")
        .format("YYYY-MM");
    } else if (timeFormat == "years") {
      xAxis[index] = Moment(startTime)
        .add(index, "years")
        .format("YYYY");
    }
  }

  return xAxis;
}

/**
 * 根据X坐标数组生成对应的Y坐标数组
 * @param  xArr: 上面getXAxis()方法返回的X坐标（时间轴坐标）数组;
 *  list:[{xAxis:"2017-03-01", yAxis:"200"},{xAxis:"2017-03-02", yAxis:"100"},...]  后台返回的坐标点数组，按时间升序排列
 */

function buildYAxis(xArr, list) {
  var len = xArr.length;
  var yAxis = new Array(len);
  var j = 0;
  listLen = list.length;
  for (i in xArr) {
    if (j < listLen && xArr[i] == list[j].xAxis) {
      yAxis[i] = list[j].yAxis;
      j++;
    } else {
      yAxis[i] = 0;
    }
  }

  return yAxis;
}

// 1.用于判断当前变量的值是否为 null 或 undefined 类型。
function isNull(val) {
  return val == undefined || val == null;
}

// 2.用于检查当前的值是否为数字类型。
function isNumber(val) {
  return !isNaN(parseFloat(val)) && isFinite(val);
}

// 3.用于判断参数的值是否是对象
function isObject(val) {
  return val == Object(val);
}

// 4.用于检查当前的值是否为字符串类型。
function isString(val) {
  return typeof val === "string";
}

// 5.用于检查当前的值是否为数组。
function isArray(val) {
  if (Array.isArray) {
    return Array.isArray(val);
  } else {
    return Object.prototype.toString.call(val) == "[object Array]";
  }
}

// 6.用于判断参数的值是否是 Symbol 类型。
function isSymbol(val) {
  return typeof val === "symbol";
}

function buildLinkSelect(lists, lv1key, lv2Key) {
  let lv1 = buildSelectOption(lists, lv1key);
  let lv2 = buildSecondSelectOption(lists, lv1key, lv2Key);
  return {
    lv1,
    lv2
  };
}

function buildSelectOption(lists, lv1key) {
  let _lists = [];
  _lists = lists.map((item, index) => {
    return {
      label: item[lv1key],
      value: item[lv1key]
    };
  });
  return _lists;
}

function buildSecondSelectOption(lists, lv1Key, lv2Key) {
  let listsObj = {};
  lists.forEach((item, index) => {
    listsObj[item[lv1Key]] = item[lv2Key].map((item2, index2) => {
      return {
        label: item2,
        value: item2
      };
    });
  });
  return listsObj;
}

function formatPictureIds(lists) {
  let idLists = [];
  if (lists.length > 0) {
    lists.forEach((item, index) => {
      idLists.push(item.uid);
    });
    return idLists;
  } else {
    return [];
  }
}

async function initUserInfo(_this) {
  _this.userName = localStorage.getItem("phone");
  if (!_this.userName) {
    _this.$router.push("/");
  } else {
    return new Promise(async (resolve, reject) => {
      const res = await api.getRoleId({ phoneNumber: _this.userName });
      if (res.MsgCode !== 0) {
        _this.$message.error("获取用户信息失败");
        reject("getRoleId erroe");
      } else {
        _this.name = res.Data.name;
        _this.role = res.Data.ID;
        _this.compId = res.Data.compid;
        resolve();
      }
    });
  }
}

// 根据登陆的手机号获取角色id;该方法适用于子组件获取user信息
function getRoleId(_this) {
  _this.userName = localStorage.getItem("phone");
  let { ID, compid, name } = JSON.parse(localStorage.getItem("userInfo"));
  _this.name = name;
  _this.role = ID;
  _this.compId = compid;
}

// 下拉框组件过滤用的函数
function filterSelectLists(input, option) {
  let str = input.replace(/\s*/g, "");
  let name = option.componentOptions.children[0].text;

  if (name == "" || name == undefined || str == "" || str == undefined) {
    return false;
  } else {
    let isMatch = name.indexOf(str) >= 0;
    return isMatch;
  }
}

export {
  buildDateAxis,
  buildLinkSelect,
  initUserInfo,
  getRoleId,
  isNull,
  isNumber,
  isObject,
  isString,
  isArray,
  isSymbol,
  formatPictureIds,
  filterSelectLists
};
